package com.zrrd.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zrrd.reggie.bean.ShoppingCart;
import com.zrrd.reggie.bean.User;
import com.zrrd.reggie.common.BaseContext;
import com.zrrd.reggie.common.R;
import com.zrrd.reggie.common.SMSUtils;
import com.zrrd.reggie.common.ValidateCodeUtils;
import com.zrrd.reggie.service.UserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;
    @PostMapping("sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpServletRequest request){
        String phone=user.getPhone();
        if (StringUtils.isNotEmpty(phone)){
            Integer code= ValidateCodeUtils.generateValidateCode(4);
            System.out.println("生成的验证码："+code);
            //SMSUtils.sendMessage("ABC商城","SMS_463600053",phone,code+"");
            //request.getSession().setAttribute("code",code+"");
            redisTemplate.opsForValue().set(phone,code+"",5, TimeUnit.MINUTES);
            return R.sucess("短信验证码发送成功");
        }
        return R.error("短信验证码发送失败");
    }
    @PostMapping("login")
    public R<User> login(@RequestBody Map map, HttpServletRequest request){
        String phone=map.get("phone").toString();
        String code=map.get("code").toString();
        //String sessionCode = (String) request.getSession().getAttribute("code");
        String redisCode= (String) redisTemplate.opsForValue().get(phone);
        if (redisCode!=null&& redisCode.equals(code)){
            QueryWrapper<User> wrapper=new QueryWrapper<>();
            wrapper.eq("phone",phone);
            User user=userService.getOne(wrapper);
            if (user == null){
                user=new User();
                user.setPhone(phone);
                user.setStatus(1);
                userService.save(user);
            }
            request.getSession().setAttribute("userId",user.getId());
            redisTemplate.delete(phone);
            return R.sucess(user);
        }else {
            return R.error("验证码错误");
        }
    }

    @PostMapping("loginout")
    public R<String> logout(HttpServletRequest request){
        request.getSession().removeAttribute("user_id");
        System.out.println("你好git");
        return R.sucess("推出成功");
    }


}
